package com.xj.api.bussiness.wxLogin.web;

import com.alibaba.fastjson.JSONObject;
import com.xj.api.base.web.BaseController;
import com.xj.api.bussiness.userInfo.service.ITbUserInfoService;
import com.xj.api.bussiness.wxLogin.service.IWxLoginService;
import com.xj.common.base.common.bean.AbstractBean;
import com.xj.common.bussiness.userInfo.entity.TbUserInfo;
import com.xj.common.bussiness.wxLogin.entity.WxLoginMould;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

/**
 * 微信用户登录接口
 */
@RestController
@RequestMapping("wxUserLog")
public class wxLoginController extends BaseController {

    @Autowired
    private IWxLoginService wxLoginService;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private ITbUserInfoService userInfoService;

    @GetMapping("/login")
    @ApiOperation(value = "  微信用户登录", httpMethod = "GET", notes = "  微信用户登录")
    public AbstractBean login(WxLoginMould wxLoginMould){
        TbUserInfo userInfo = new TbUserInfo();
        userInfo.setIdentification(wxLoginMould.getIdentification());
        List<TbUserInfo>  list = userInfoService.getUserInfoByCondition(userInfo);
        for (TbUserInfo entity:list ) {
            userInfo = entity;
        }
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+wxLoginMould.getAppid()+"&secret="+wxLoginMould.getSecret()+"&js_code=" + wxLoginMould.getJs_code() + "&grant_type="+wxLoginMould.getGrant_type();
        HashMap<String, Object> bean = wxLoginService.GET(url);
        if(bean.get("status").toString().equals("OK")){
            String key = bean.get("openid").toString();
            userInfo.setWxUser(key);
            userInfoService.insertOrUpdate(userInfo);
            //根据用户的openid取出session中的数据
            JSONObject object =(JSONObject) request.getSession().getAttribute(key);
            String openid = object.get("openid").toString();
            //String session_key = object.get("session_key").toString();
            return json(openid);
        }
        return error();
    }
}
